package com.gears.ffmpeg;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gears.core.util.PropertyUtil;
/**
 * 转换服务
 * ConvertServlets.java
 * @author Administrator
 * @version 2016年8月10日
 */
public class ConvertServlets extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * post - 方法
	 * 内部调用get方法 - 统一处理
	 */
	public void doPost(HttpServletRequest request,
			HttpServletResponse response)throws ServletException, IOException{
		doGet(request, response);
	}
	/**
	 * get - 方法
	 * 
	 */
	public void doGet(HttpServletRequest request,
			HttpServletResponse response)
			throws ServletException, IOException {
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			//String uri = request.getRequestURI();
			//out.println(ServletUtilities.headWithTitle("Test Servlet") +"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H2>URI: " + uri "</H2>\n" +"</BODY></HTML>");
			
			ConvertServlets me = new ConvertServlets();
			String sourceUrl = request.getParameter("sourceUrl");
			String command = request.getParameter("command");
			System.out.println("url : " + sourceUrl);
			if(!request.getParameter("type").equals("-1")){
				out.print("data:{code:202,msg:type error}");
				return;
			}
			// 指定MP4格式
			String infile = sourceUrl;
			UUID uuid = UUID.randomUUID();
			String outfile = "/tmp/" + uuid + ".mp4";
			
	        String timelen = me.readtime(infile);
	        System.out.println("timelen is :" + timelen);

	        if(me.transfer(infile,outfile,command)) {
	            System.out.println("the transfer is ok!");
	        } else {
	            System.out.println("the transfer is error!");
	            out.print("data:{code:201,msg:convert error}");
	            return;
	        }
	        String res = "data:{code:200,msg:succss,url:" + outfile + ",data:" + "" + "}";
	        out.print(res);
	}
	
	public void runCmd(String command) {
        try {

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ( (line = br.readLine()) != null)
                System.out.println(line);

            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    public boolean transfer(String infile,String outfile,String command) {
    	BufferedReader br = null;
    	int i = infile.lastIndexOf(".");
    	String format = infile.subSequence(i+1, infile.length()).toString();
    	String formatTomp4 = "";
    	//String avitoflv = "ffmpeg -i "+infile+" -ar 22050 -ab 56 -f flv -y -s 320x240 "+outfile;
        //String flvto3gp = "ffmpeg -i " + infile + " -ar 8000 -ac 1 -acodec amr_nb -vcodec h263 -s 176x144 -r 12 -b 30 -ab 12 " + outfile;
        //String avito3gp = "ffmpeg -i " + infile + " -ar 8000 -ac 1 -acodec amr_nb -vcodec h263 -s 176x144 -r 12 -b 30 -ab 12 " + outfile;
        //String avitojpg = "ffmpeg -i " + infile + " -y -f image2 -ss 00:00:10 -t 00:00:01 -s 350x240 " + outfile;
//        String flvTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -vcodec libx264 " + outfile;
        String flvTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -ab 56 -ar 22050 -qscale 8 -r 15 -s 1280*720 " + outfile;

        //String aviTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -vcodec libx264 " + outfile;
        String aviTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -ab 56 -ar 22050 -qscale 8 -r 15 -s 1280*720 " + outfile;

        //String movTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -vcodec libx264 " + outfile;
        String movTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i " + infile + " -ab 56 -ar 22050 -qscale 8 -r 15 -s 1280*720 " + outfile;

        //String mp4Tomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i "+infile+ " -ar 22050 -ab 56 -f flv -s 320x240 " +outfile;
        String mp4Tomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i "+infile+ " -ab 56 -ar 22050 -qscale 8 -r 15 -s 1280*720 " +outfile;

        //String wmvTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i "+infile+ " -vcodec libx264 " + outfile;
        String wmvTomp4 =PropertyUtil.getConfigureProperties("mv_mp4_command") + " -i "+infile+ " -ab 56 -ar 22050 -qscale 8 -r 15 -s 1280*720 " + outfile;

        if (command != null && !"".equals(command)){
        	formatTomp4 = command;
        } else if("flv".equalsIgnoreCase(format)){
    		formatTomp4 = flvTomp4;
    	} else if ("avi".equalsIgnoreCase(format)){
    		formatTomp4 = aviTomp4;
    	} else if ("mov".equalsIgnoreCase(format)) {
    		formatTomp4 = movTomp4;
    	} else if ("mp4".equalsIgnoreCase(format)) {
    		formatTomp4 = mp4Tomp4;
    	} else if("wmv".equalsIgnoreCase(format)){
    		formatTomp4 = wmvTomp4;
    	}
    	System.out.println(formatTomp4);
    	
    	if("".equals(formatTomp4)){
    		return false;
    	}
    	
    	 System.out.println("formatTomp4 : " + formatTomp4);

        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(formatTomp4);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            br = new BufferedReader(isr);
            String line = null;

            while ( (line = br.readLine()) != null)
                System.out.println(line);

            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
            
        } catch (Throwable t) {
            t.printStackTrace();
            return false;
        }finally{
        	if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
        }
        return true;
    }

    public static String readFile(String fileName,int id) {
        String dataStr = "";
        FileInputStream fis = null;
        try {
            FileReader file = new FileReader(fileName);//建立FileReader对象，并实例化为fr
            BufferedReader br=new BufferedReader(file);//建立BufferedReader对象，并实例化为br
            String Line=br.readLine();//从文件读取一行字符串
            dataStr=Line;
            br.close();//关闭BufferedReader对象
        } catch(Exception e) {

        } finally {
            try {
                if(fis!=null)
                    fis.close();
            } catch(Exception e) {}
        }
        return dataStr;
    }

    public String readtime(String file) {
        // String str="/root/Desktop/info.txt";
    	//String str="/tmp/info.txt";
        String timelen = "";
        String cmd = "cmd /c timelen "+file;
        runCmd(cmd);
        timelen=readFile(file,1);
        return timelen;
    }

    public static void main(String args[]) {
    	ConvertServlets me = new ConvertServlets();

		String infile = "F:\\360Downloads\\Software\\3.avi";
        String outfile = "F:\\360Downloads\\Software\\3.mp4";

        String timelen = me.readtime(infile);
        System.out.println("timelen is :" + timelen);

        if(me.transfer(infile,outfile,"")) {
            System.out.println("the transfer is ok!");
        } else {
            System.out.println("the transfer is error!");
        }
//    	String u = "20.220.23.2321:2020/sfsfdsfs.mp4";
//
//    	int i = u.lastIndexOf(".");
//    	String ewewe = u.subSequence(i+1, u.length()).toString();
//    	System.out.println(u.subSequence(i+1, u.length()) + ewewe);
    }
			
	
}
